package com.ruoyi.industry.service.impl;

import java.util.*;

import com.ruoyi.common.core.constant.SecurityConstants;
import com.ruoyi.common.core.exception.ServiceException;
import com.ruoyi.common.core.utils.DateUtils;
import com.ruoyi.common.core.utils.StringUtils;
import com.ruoyi.common.core.utils.uuid.IdUtils;
import com.ruoyi.common.security.utils.SecurityUtils;
import com.ruoyi.industry.domain.District;
import com.ruoyi.industry.domain.ProjectPark;
import com.ruoyi.industry.domain.SpaceIndustry;
import com.ruoyi.industry.mapper.*;
import com.ruoyi.industry.utils.EntrustUtil;
import com.ruoyi.system.api.RemoteFileService;
import com.ruoyi.system.api.domain.PathVo;
import com.ruoyi.system.api.domain.SysUser;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.industry.domain.ProjectWarehouse;
import com.ruoyi.industry.service.IProjectWarehouseService;

import javax.servlet.http.HttpServletResponse;

/**
 * 项目-仓库Service业务层处理
 *
 * @author MagicCube
 * @date 2023-05-08
 */
@Service
public class ProjectWarehouseServiceImpl implements IProjectWarehouseService
{
    private static final Logger log = LoggerFactory.getLogger(ProjectAuctionServiceImpl.class);

    @Autowired
    private ProjectWarehouseMapper projectWarehouseMapper;

    @Autowired
    private SpaceIndustryMapper spaceIndustryMapper;

    @Autowired
    private DistrictMapper districtMapper;

    @Autowired
    private SpaceCollectMapper spaceCollectMapper;

    @Autowired
    private ProjectParkMapper projectParkMapper;

    @Autowired
    private RemoteFileService remoteFileService;
    /**
     * 查询项目-仓库
     *
     * @param id 项目-仓库主键
     * @return 项目-仓库
     */
    @Override
    public ProjectWarehouse selectProjectWarehouseById(Long id)
    {
        return projectWarehouseMapper.selectProjectWarehouseById(id);
    }

    /**
     * 查询项目-仓库列表
     *
     * @param projectWarehouse 项目-仓库
     * @return 项目-仓库
     */
    @Override
    public List<ProjectWarehouse> selectProjectWarehouseList(ProjectWarehouse projectWarehouse)
    {
        List<ProjectWarehouse> projectWarehouseList = projectWarehouseMapper.selectProjectWarehouseList(projectWarehouse);
        for (ProjectWarehouse warehouse : projectWarehouseList) {
            SysUser sysUser = spaceIndustryMapper.selectSysUserById(warehouse.getServicePhone());
            if (sysUser!=null) {
                warehouse.setContactName(sysUser.getNickName());
                warehouse.setContactPhone(sysUser.getPhonenumber());
            }
        }
        return projectWarehouseList;
    }
    @Override
    public List<ProjectWarehouse> selectProjectWarehouseListz(ProjectWarehouse projectWarehouse)
    {
        //应急系统
//        if (projectWarehouse.getWareEmergency() != null && projectWarehouse.getWareEmergency().equals("H")) {
//            projectWarehouse.setWareEmergency("有");
//        } else if (projectWarehouse.getWareEmergency() != null && projectWarehouse.getWareEmergency().equals("N")) {
//            projectWarehouse.setWareEmergency("无");
//        }
//        List<Long> districtIds = new ArrayList<Long>();
//        //城市
//        if (projectWarehouse.getCityId()!=null){
//            districtIds.add(projectWarehouse.getCityId());
//            projectWarehouse.setCityIds(districtIds);
//        }else if (projectWarehouse.getCityId()==null && projectWarehouse.getProvinceId() != null){
//            //查询省份下的城市
//            districtIds.addAll(districtMapper.selectDistrictIdList(projectWarehouse.getProvinceId()));
//            districtIds.add(projectWarehouse.getProvinceId());
//            projectWarehouse.setCityIds(districtIds);
//        }
        //售价
        if (projectWarehouse.getWareSellPrice()!=null){
            String[] split = projectWarehouse.getWareSellPrice().split("~");
            projectWarehouse.setWareSellPriceLow(Long.parseLong(split[0]));
            if (!split[1].equals("N")) {
                projectWarehouse.setWareSellPriceHigh(Long.parseLong(split[1]));
            }
        }
        //租价
        if(projectWarehouse.getWareLeasePrice()!=null){
            String[] split = projectWarehouse.getWareLeasePrice().split("~");
            projectWarehouse.setWareLeasePriceLow(Long.parseLong(split[0]));
            if (!split[1].equals("N")) {
                projectWarehouse.setWareLeasePriceHigh(Long.parseLong(split[1]));
            }
        }
//        if (!SecurityUtils.getLoginUser().getRoles().contains("admin")){
//            projectWarehouse.setSupplyUserId(SecurityUtils.getUserId());
//        }
        return projectWarehouseMapper.selectProjectWarehouseListz(projectWarehouse);
    }

    /**
     * 新增项目-仓库
     *
     * @param projectWarehouse 项目-仓库
     * @return 结果
     */
    @Override
    public int insertProjectWarehouse(ProjectWarehouse projectWarehouse)
    {
        projectWarehouse.setSupplyUserId(SecurityUtils.getUserId());//发布人ID
        if (projectWarehouse.getApprovalState()==null) {
//            if (SecurityUtils.getLoginUser().getRoles().contains("admin")) {
//                projectWarehouse.setApprovalState(1L);//审核通过
//            } else {
                projectWarehouse.setApprovalState(0L);
//            }
        }
        projectWarehouse.setCreateTime(DateUtils.getNowDate());
        projectWarehouse.setSerialNumber(IdUtils.fastSimpleUUID());
        SpaceIndustry spaceIndustry = new SpaceIndustry();
        extracted(projectWarehouse, spaceIndustry);
        spaceIndustry.setSupplyUserId(projectWarehouse.getSupplyUserId());
        spaceIndustry.setCreateBy(SecurityUtils.getUsername());
        spaceIndustry.setCreateTime(projectWarehouse.getCreateTime());
        spaceIndustry.setSpaceId(projectWarehouse.getSerialNumber());
        spaceIndustryMapper.insertSpaceIndustry(spaceIndustry);
        return projectWarehouseMapper.insertProjectWarehouse(projectWarehouse);
    }

    private static void extracted(ProjectWarehouse projectWarehouse, SpaceIndustry spaceIndustry) {
        spaceIndustry.setBuildType(4);
        spaceIndustry.setReleaseType(projectWarehouse.getReleaseType());
        spaceIndustry.setApprovalState(projectWarehouse.getApprovalState());
        spaceIndustry.setProvinceId(projectWarehouse.getProvinceId());//省份
        spaceIndustry.setCityId(projectWarehouse.getCityId());//城市
//        spaceIndustry.setAreaId();//区域
        spaceIndustry.setSupplyType(projectWarehouse.getSupplyType());//服务类型
        spaceIndustry.setParkId(String.valueOf(projectWarehouse.getParkId()));
        spaceIndustry.setHeating(projectWarehouse.getWareHeating());//供暖
        spaceIndustry.setRefrig(projectWarehouse.getWareRefrig());//制冷
        spaceIndustry.setPower(projectWarehouse.getWarePower());//电力
        spaceIndustry.setGas(projectWarehouse.getWareGas());//燃气
        spaceIndustry.setLeasePrice(projectWarehouse.getWareLeasePrice());//出售价格
        spaceIndustry.setSellPrice(projectWarehouse.getWareSellPrice());//租赁价格
        spaceIndustry.setCoverResource(projectWarehouse.getCoverResource());//封面资源
        spaceIndustry.setSpaceName(projectWarehouse.getWareName());//空间名称
        spaceIndustry.setSpaceAllSize(projectWarehouse.getWareAllSize());//空间总面积
        spaceIndustry.setTop(projectWarehouse.getTop());//置顶
        spaceIndustry.setRecomState(projectWarehouse.getRecomState());//热门推荐
    }

    /**
     * 修改项目-仓库
     *
     * @param projectWarehouse 项目-仓库
     * @return 结果
     */
    @Override
    public int updateProjectWarehouse(ProjectWarehouse projectWarehouse)
    {
        if (projectWarehouse.getApprovalState()==null){
            projectWarehouse.setApprovalState(0L);
        }
        projectWarehouse.setUpdateTime(DateUtils.getNowDate());
        SpaceIndustry spaceIndustry = new SpaceIndustry();
        extracted(projectWarehouse,spaceIndustry);
        spaceIndustry.setSpaceId(String.valueOf(projectWarehouse.getId()));
        spaceIndustry.setUpdateBy(SecurityUtils.getUsername());
        spaceIndustry.setUpdateTime(projectWarehouse.getUpdateTime());
        spaceIndustryMapper.updateSpaceIndustryByWarehouseId(spaceIndustry);
        return projectWarehouseMapper.updateProjectWarehouse(projectWarehouse);
    }

    /**
     * 批量删除项目-仓库
     *
     * @param ids 需要删除的项目-仓库主键
     * @return 结果
     */
    @Override
    public int deleteProjectWarehouseByIds(Long[] ids)
    {
        List<String> pathList = new ArrayList<>();
        for (ProjectWarehouse projectWarehouse : projectWarehouseMapper.selectProjectWarehouseByIds(ids)) {
            spaceIndustryMapper.deleteSpaceRecomById("仓库",projectWarehouse.getId());
            SpaceIndustryServiceImpl.deleteFile(
                    pathList,
                    projectWarehouse.getVrResource(),
                    projectWarehouse.getImgResource(),
                    projectWarehouse.getCoverResource(),
                    projectWarehouse.getVrcover(),
                    projectWarehouse.getQrCode()
            );
        }
        remoteFileService.delete(new PathVo(pathList), SecurityConstants.INNER);
        spaceIndustryMapper.deleteSpaceIndustryByProjectWarehouseIds(ids);
        return projectWarehouseMapper.deleteProjectWarehouseByIds(ids);
    }

    /**
     * 删除项目-仓库信息
     *
     * @param id 项目-仓库主键
     * @return 结果
     */
    @Override
    public int deleteProjectWarehouseById(Long id)
    {
        ProjectWarehouse projectWarehouse = projectWarehouseMapper.selectProjectWarehouseById(id);
        List<String> pathList = new ArrayList<>();
        SpaceIndustryServiceImpl.deleteFile(
                pathList,
                projectWarehouse.getVrResource(),
                projectWarehouse.getImgResource(),
                projectWarehouse.getCoverResource(),
                projectWarehouse.getVrcover(),
                projectWarehouse.getQrCode()
        );
        spaceIndustryMapper.deleteSpaceRecomById("仓库",projectWarehouse.getId());
        remoteFileService.delete(new PathVo(pathList), SecurityConstants.INNER);
        spaceIndustryMapper.deleteSpaceIndustryByProjectWarehouseId(id);
        return projectWarehouseMapper.deleteProjectWarehouseById(id);
    }

    @Override
    public Map<String, Object> selectProjectWarehouseByNumber(String spaceId, boolean show) {
        ProjectWarehouse projectWarehouse = projectWarehouseMapper.selectProjectWarehouseByNumber(spaceId);
        if (SecurityUtils.getUserId()!=null&&SecurityUtils.getUserId()!=0) {
            List<String> list = spaceCollectMapper.selectSpaceCollectByUserId(SecurityUtils.getUserId(), spaceId);
            if (show) {
                spaceIndustryMapper.updatePageViews(spaceId);
                projectWarehouseMapper.updatePageViews(spaceId);
            }
            if (list != null && list.size() != 0) {
                projectWarehouse.setCollectState(1L);
            } else {
                projectWarehouse.setCollectState(0L);
            }
        }else {
            projectWarehouse.setCollectState(0L);
        }
        if (projectWarehouse.getProvinceId()!=null){
            District district = districtMapper.selectDistrictById(projectWarehouse.getProvinceId());
            projectWarehouse.setCityName(district.getName());
        }
        if (projectWarehouse.getCityId()!=null){
            District district = districtMapper.selectDistrictById(projectWarehouse.getCityId());
            projectWarehouse.setCityName(projectWarehouse.getCityName()+district.getName());
        }
        SysUser sysUser = spaceIndustryMapper.selectSysUserById(projectWarehouse.getServicePhone());
        if (sysUser!=null){
            projectWarehouse.setContactName(sysUser.getNickName());
            projectWarehouse.setContactPhone(sysUser.getPhonenumber());
            projectWarehouse.setQrCode(sysUser.getCodePic());
        }
//        if (projectWarehouse.getAreaId()!=null){
//            District district = districtMapper.selectDistrictById(projectWarehouse.getAreaId());
//            projectWarehouse.setCityName(projectWarehouse.getCityName()+district.getName());
//        }
        SpaceIndustry spaceIndustry = spaceIndustryMapper.selectSpaceIndustryBySpaceId(spaceId);
        if (spaceIndustry!=null){
            projectWarehouse.setPageView(Long.valueOf(spaceIndustry.getPageViews()));
        }
        Map<String, Object> map = new HashMap<>();
        map.put("space",projectWarehouse);
        if (projectWarehouse.getParkId()!=null) {
            ProjectPark projectPark = projectParkMapper.selectProjectParkById(projectWarehouse.getParkId());
            map.put("park",projectPark);
        }else {
            map.put("park",null);
        }
        return map;
    }

    @Override
    public int deleteProjectWarehouseBySerialNumber(String spaceId) {
        ProjectWarehouse projectWarehouse = projectWarehouseMapper.selectProjectWarehouseByNumber(spaceId);
        List<String> pathList = new ArrayList<>();
        SpaceIndustryServiceImpl.deleteFile(
                pathList,
                projectWarehouse.getVrResource(),
                projectWarehouse.getImgResource(),
                projectWarehouse.getCoverResource(),
                projectWarehouse.getVrcover(),
                projectWarehouse.getQrCode()
        );
        remoteFileService.delete(new PathVo(pathList), SecurityConstants.INNER);
        spaceIndustryMapper.deleteSpaceRecomById("仓库",projectWarehouse.getId());
        spaceIndustryMapper.deleteSpaceIndustryByProjectWarehouseId(projectWarehouse.getId());
        return projectWarehouseMapper.deleteProjectWarehouseById(projectWarehouse.getId());
    }

    private static final List<Long> STATE = Arrays.asList(0L,1L,2L,3L);
    @Override
    public String importUser(List<ProjectWarehouse> projectWarehouseList, boolean updateSupport, String operName) {
        if (StringUtils.isNull(projectWarehouseList) || projectWarehouseList.size() ==0){
            throw new ServiceException("导入数据不能为空！");
        }
        int successNum = 0;
        int failureNum = 0;
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();
        Long count = 0L;
        for (ProjectWarehouse projectWarehouse : projectWarehouseList) {
            if (projectWarehouseList.indexOf(projectWarehouse)==0&&projectWarehouse.getWareName().equals("仓库名称")){
                continue;
            }
            count++;
            try {
                if (projectWarehouse.getApprovalState()==null||STATE.contains(projectWarehouse.getApprovalState())){
                    projectWarehouse.setApprovalState(0L);
                }
                if (projectWarehouse.getSupplyUserId()==null){
                    projectWarehouse.setSupplyUserId(SecurityUtils.getUserId());
                }
                if (projectWarehouse.getWareName()==null||projectWarehouse.getWareName().equals("")){
                    failureNum++;
                    failureMsg.append("<br/>" + failureNum + "、第 " + count + "条数据 缺少仓库名称");
                    break;
                }
                projectWarehouse.setCreateBy(SecurityUtils.getUsername());
                projectWarehouse.setCreateTime(DateUtils.getNowDate());
                projectWarehouseMapper.insertProjectWarehouse(projectWarehouse);
                successNum++;
                successMsg.append("<br/>" + successNum + "、仓库 " + projectWarehouse.getWareName() + " 导入成功");
            }catch (Exception e) {
                failureNum++;
                String msg = "<br/>" + failureNum + "、仓库 " + projectWarehouse.getWareName() + " 导入失败：";
                failureMsg.append(msg + e.getMessage());
                log.error(msg, e);
            }
        }
        if (failureNum > 0)
        {
            failureMsg.insert(0, "很抱歉，导入失败！共 " + failureNum + " 条数据格式不正确，错误如下：");
            throw new ServiceException(failureMsg.toString());
        }
        else
        {
            successMsg.insert(0, "恭喜您，数据已全部导入成功！共 " + successNum + " 条，数据如下：");
        }
        return successMsg.toString();
    }

    @Override
    public void exportEntrust(HttpServletResponse response, Long id) {
        ProjectWarehouse modal = projectWarehouseMapper.selectProjectWarehouseById(id);
        StringBuffer stringBuffer = new StringBuffer();
        stringBuffer.append("仓库名称：" + modal.getWareName() + "<w:br/>");
        stringBuffer.append("供给类型：" + modal.getSupplyType() + "<w:br/>");
        stringBuffer.append("租赁价格：" + modal.getWareLeasePrice() + "<w:br/>");
        stringBuffer.append("出售价格：" + modal.getWareSellPrice() + "<w:br/>");
        stringBuffer.append("总面积：" + modal.getWareAllSize() + "<w:br/>");
        stringBuffer.append("空置面积：" + modal.getWorkFreeSize() + "<w:br/>");
        stringBuffer.append("所在楼层：" + modal.getWareFloor() + "<w:br/>");
        stringBuffer.append("层高：" + modal.getWareFloorHeight() + "<w:br/>");
        stringBuffer.append("首层承重：" + modal.getWareFirstLoad() + "<w:br/>");
        stringBuffer.append("标准层承重：" + modal.getWareLoad() + "<w:br/>");
        stringBuffer.append("设施：" + modal.getWareFacili() + "<w:br/>");
        stringBuffer.append("货梯：" + modal.getWareElevatorCargo() + "<w:br/>");
        stringBuffer.append("货梯负载：" + modal.getWareElevatorCargoLoad() + "<w:br/>");
        stringBuffer.append("消防设施：" + modal.getWareFireControl() + "<w:br/>");
        stringBuffer.append("应急系统：" + modal.getWareEmergency() + "<w:br/>");
        stringBuffer.append("供暖：" + modal.getWareHeating() + "<w:br/>");
        stringBuffer.append("制冷：" + modal.getWareRefrig() + "<w:br/>");
        stringBuffer.append("电量：" + modal.getWarePower() + "<w:br/>");
        stringBuffer.append("燃气：" + modal.getWareGas() + "<w:br/>");
        stringBuffer.append("水：" + modal.getWareWater() + "<w:br/>");
        stringBuffer.append("园区类别：" + modal.getParkType() + "<w:br/>");
        stringBuffer.append("区域位置：" + modal.getParkAreaAddress() + "<w:br/>");
        stringBuffer.append("需求面积：" + modal.getWareNeedSize() + "<w:br/>");
        stringBuffer.append("联系人：" + modal.getContactName() + "<w:br/>");
        stringBuffer.append("联系方式：" + modal.getContactPhone() + "<w:br/>");
        new EntrustUtil().exportWord(stringBuffer,response);
    }
}
